<template>
  <g-tree
    ref="tree"
    :fetch="fetch"
    @fetch-success="fetchSuccess"
    showIcon
    draggable
    block-node
    :multiple="false"
    @select="onSelect"
    @rightClick="onRightClick"
    @dragstart="DragStart"
    @drop="DragEnd"
  >
    <template #headerTitle>{{ l('OrganizationTree') }}</template>
    <template #headerExtra>
      <a-space>
        <a @click="handleAddClick">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#gctxinjian"></use>
          </svg>
          {{ l('AddRootUnit') }}
        </a>
        <a @click="reload()">
          <slot name="reload-extra">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#gctshuaxin3"></use>
            </svg>
          </slot>
        </a>
      </a-space>
    </template>
    <template #title="{ title, key }">
      <a-dropdown :trigger="['contextmenu']">
        <span>{{ title }}</span>
        <template #overlay>
          <a-menu @click="({ key: menuKey }) => onContextMenuClick(key, menuKey)">
            <a-menu-item key="Edit">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#gctbianji"></use>
              </svg>
              {{ l('Edit') }}
            </a-menu-item>
            <a-menu-item key="AddSubUnit">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#gctxinjian"></use>
              </svg>
              {{ l('AddSubUnit') }}
            </a-menu-item>
            <a-menu-item key="Delete">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#gctshanchu3"></use>
              </svg>
              {{ l('Delete') }}
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </template>
  </g-tree>
  <!-- <create-or-edit-organiaztion-unit
    ref="createOrEditRef"
    :pageDataList="pageDataList"
    @closeFn="reload"
  ></create-or-edit-organiaztion-unit> -->
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import GTree from '/@/shared/components/g-tree/index.vue';
  import { AppComponentBase } from '/@/shared/component-base';
  import {
    MoveOrganizationUnitInput,
    OrganizationUnitListDto,
    OrganizationUnitServiceProxy,
  } from '/@/shared/service-proxies';
  import _ from 'lodash';
  import { Modal } from 'ant-design-vue';
  import CreateOrEditOrganiaztionUnit from '../create-or-edit-organization-unit/create-or-edit-organization-unit.vue';
  export default defineComponent({
    name: 'organizaion-unit-tree-panel',
    components: { GTree, CreateOrEditOrganiaztionUnit },
    mixins: [AppComponentBase],
    data() {
      return {
        organizationUnitServiceProxy: new OrganizationUnitServiceProxy(),
        ouData: new Array<OrganizationUnitListDto>(),
        NodeTreeItem: null, // 右键菜单
        tmpStyle: {},
        // 选中的item
        activedNode: {} as OrganizationUnitListDto,
        currentNode: null as any,
        currentCreateOrganization: new OrganizationUnitListDto(),
        pageDataList: [] as any,
      };
    },
    methods: {
      fetch() {
        return new Promise((resolve, reject) => {
          this.organizationUnitServiceProxy
            .getAllOrganizationUnitList()
            .then((result) => {
              resolve(result);
            })
            .catch((err) => {
              reject(err);
            });
        });
      },
      /** 刷新 */
      reload() {
        (this.$refs.tree as any).reload();
      },
      /** 新增 */
      handleAddClick() {
        this.pageDataList = [];
        this.modalHelper
          .create(CreateOrEditOrganiaztionUnit, { pageDataList: this.pageDataList })
          .subscribe((res) => {
            if (res) {
              this.reload();
            }
          });
      },
      /**
       * 编辑组织机构
       */
      editUnit() {
        const canManageOrganizationTree = this.isGranted(
          'Pages.Administration.OrganizationUnits.ManageOrganizationTree',
        );
        if (!canManageOrganizationTree) {
          this.message.error(this.l('YouHaveNoOperatingPermissions'));
          return;
        }
        if (!!this.activedNode) {
          const obj = {
            id: parseInt(this.activedNode.id),
            displayName: this.activedNode.displayName,
          };
          this.pageDataList = !!obj ? [obj] : [];
          this.modalHelper
            .create(CreateOrEditOrganiaztionUnit, { pageDataList: this.pageDataList })
            .subscribe((res) => {
              if (res) {
                this.reload();
              }
            });
        }
      },
      /**
       * 添加子节点
       * @param node 当前选中节点
       */
      addSubUnit(treeKey) {
        const canManageOrganizationTree = this.isGranted(
          'Pages.Administration.OrganizationUnits.ManageOrganizationTree',
        );
        if (!canManageOrganizationTree) {
          this.notify.success(this.l('YouHaveNoOperatingPermissions'));
          return;
        }
        if (treeKey) {
          const obj = !!treeKey
            ? {
                parentId: treeKey,
              }
            : null;
          this.pageDataList = !!obj ? [obj] : [];
          this.modalHelper
            .create(CreateOrEditOrganiaztionUnit, { pageDataList: this.pageDataList })
            .subscribe((res) => {
              if (res) {
                this.reload();
              }
            });
        }
      },
      onRightClick({ node }) {
        this.activedNode = this.ouData.find(
          (item) => item.id == node.dto.id,
        ) as OrganizationUnitListDto;
      },
      /**
       * 删除组织结构
       */
      deleteconfirm(treeKey) {
        const canManageOrganizationTree = this.isGranted(
          'Pages.Administration.OrganizationUnits.ManageOrganizationTree',
        );
        if (!canManageOrganizationTree) {
          this.notify.success(this.l('YouHaveNoOperatingPermissions'));
          return;
        }
        if (treeKey) {
          (this.$refs.tree as any).setLoading(true);
          this.organizationUnitServiceProxy
            .delete(parseInt(treeKey))
            .then(() => {
              this.notify.success(this.l('SuccessfullyDeleted'));
              this.clearMenu();
            })
            .finally(() => {
              this.reload();
            });
        }
      },
      onContextMenuClick(treeKey, menuKey) {
        const deleteconfirm = () => {
          this.deleteconfirm(treeKey);
        };
        switch (menuKey) {
          case 'AddSubUnit':
            this.addSubUnit(treeKey);
            break;
          case 'Delete':
            Modal.confirm({
              title: this.l('ConfirmDeleteWarningMessage'),
              onOk() {
                deleteconfirm();
              },
              onCancel() {},
              class: 'test',
            });
            break;
          case 'Edit':
            this.editUnit();
            break;
          default:
            break;
        }
      },
      fetchSuccess(val) {
        this.ouData = val.items as Array<OrganizationUnitListDto>;
        const newTreeData = this.treeDataMap();
        (this.$refs.tree as any).setTreeDataList(newTreeData);
      },
      /**
       * 重组Tree数据
       */
      treeDataMap() {
        const ouDtataParentIsNull = _.filter(this.ouData, (item) => item.parentId === null);
        return ouDtataParentIsNull.map((item) => this._recursionGenerateTree(item));
      },

      /**
       * 递归重组特性菜单为nzTree数据类型
       * @param item 组织机构项
       */
      _recursionGenerateTree(item) {
        // 叶子节点
        const childs = _.filter(this.ouData, (child) => child.parentId === item.id);
        // 父节点 无返回undefined
        const parentOu = _.find(this.ouData, (p) => p.id === item.parentId);
        const _treeNode = {
          title: item.displayName + '(' + item.memberCount + ')',
          key: item.id.toString(),
          isLeaf: childs && childs.length <= 0,
          slots: {
            icon: childs && childs.length > 0 ? 'folder' : 'file',
          },
          expanded: true,
          isMatched: true,
          code: item.code,
          memberCount: item.memberCount,
          dto: item,
          parent: parentOu,
          children: [],
        };
        if (childs && childs.length) {
          childs.forEach((itemChild: any) => {
            const childItem = this._recursionGenerateTree(itemChild, childs) as never;
            _treeNode.children.push(childItem);
          });
        }
        return _treeNode;
      },
      /**
       * 选中item
       */
      onSelect(selectedKeys, _info) {
        this.activedNode = this.ouData.find(
          (item) => parseInt(item.id) == parseInt(selectedKeys[0]),
        ) as OrganizationUnitListDto;
        this.$emit('selectedNode', this.activedNode);
      },
      DragStart(node: any) {
        this.currentNode = node.node.dataRef;
      },
      DragEnd(node: any) {
        let moveid: any = null;
        if (node) moveid = node.node.dataRef.dto.id;
        if (!this.currentNode) return;
        if (node.node.dataRef.dto.id === this.currentNode.dto.id) return;
        Modal.confirm({
          title:
            '确定将' +
            this.currentNode.dto.displayName +
            '发送到' +
            node.node.dataRef.dto.displayName,
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            let moveinput: MoveOrganizationUnitInput = new MoveOrganizationUnitInput();
            moveinput.id = this.currentNode.dto.id;
            moveinput.newParentId = moveid;
            this.organizationUnitServiceProxy.move(moveinput).then(() => {
              this.clearMenu();
              this.reload();
              this.notify.success(this.l('SavedSuccessfully'));
            });
            return Promise.resolve();
          },
        });
      },
      /**
       * 用于点击空白处隐藏增删改菜单
       */
      clearMenu() {
        this.NodeTreeItem = null;
      },
    },
  });
</script>
